<!-- 个人中心 -->
<template>
  <div class="wrapper">
    <div class="block-header">
      <n-space align="center">
        <div class="title">用户管理:</div>
        <n-button
          @click="handleCreateUser"
          size="small"
          type="primary"
          secondary
          strong
          >{{ $t("add user") }}</n-button
        >
        <n-divider vertical></n-divider>
        <n-button size="small" type="info" secondary strong>{{
          $t("inport")
        }}</n-button>
        <n-button size="small" type="info" secondary strong>{{
          $t("export")
        }}</n-button>
        <!-- <n-select
          size="small"
          style="width: 180px"
          :options="sortOptions"
          v-model:value="searchParams.sort"
        ></n-select> -->
      </n-space>
      <n-space style="margin-left: auto">
        <!-- <n-input
          style="width: 150px"
          size="small"
          :placeholder="$t('please input keyword')"
        >
          <template #prefix>
            <n-icon :component="SearchOutline" />
          </template>
        </n-input>
        <n-button size="small" type="primary" secondary strong>{{
          $t("new form")
        }}</n-button> -->
      </n-space>
    </div>

    <n-divider></n-divider>
    <n-space align="center">
      <div class="row">
        <div class="row-label">角色类型</div>
        <n-select
          placeholder="请选择用户类型"
          size="small"
          style="width: 150px"
          v-model:value="searchParams.role"
        ></n-select>
      </div>
      <div class="row">
        <div class="row-label">用户名称</div>
        <n-input
          size="small"
          style="width: 150px"
          v-model:value="searchParams.username"
        ></n-input>
      </div>
    </n-space>
    <n-divider></n-divider>

    <n-data-table
      :rowKey="(row) => row.id"
      :columns="columns"
      :data="userList"
      :pagination="pagination"
    ></n-data-table>
    <formBuilder
      @submit="handleConfirm"
      ref="Upsert"
      :schema="userSchema"
    ></formBuilder>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, h } from "vue";
import centerFrame from "../components/storage/components/centerFrame.vue";
import { useRouter } from "vue-router";
import {
  SearchOutline,
  EllipsisVerticalOutline,
  DocumentTextOutline,
  ChevronBackOutline,
} from "@vicons/ionicons5";
import {
  addUser,
  deleteUser,
  getFormUsers,
  getUserDetail,
  updateUser,
} from "@/api/user";
import { NAvatar, NButton, NSpace, NSwitch, NTag } from "naive-ui";
import userSchema from "@/json/userForm.json";
import formBuilder from "@/components/form-builder/dialog.vue";
import { useMessage, useDialog } from "naive-ui";
import { useUserStore } from "@/store/user";
const userStore = useUserStore();
const message = useMessage();
const dialog = useDialog();
const Upsert = ref();
const pagination = ref({ pageSize: 10, page: 1 });
const userList = ref([]);
const router = useRouter();
const searchParams = {
  role: "",
  username: "",
};
// const options = ref([
//   {
//     label: "数据管理",
//     value: "数据管理",
//   },
//   {
//     label: "问卷填写",
//     value: "问卷填写",
//   },
// ]);
const handleBack = () => {
  router.back();
};
const columns = [
  {
    type: "selection",
    fixed: "left",
  },
  {
    title: "头像",
    key: "headImg",
    render(row) {
      return h(NAvatar, { src: row.headImg });
    },
  },
  {
    title: "用户名",
    key: "username",
  },
  {
    title: "名称(中文)",
    key: "name",
  },
  {
    title: "昵称",
    key: "nickName",
  },
  {
    title: "角色",
    key: "roleName",
    render(row) {
      return h(
        NSpace,
        { align: "center" },
        {
          default: () =>
            row.roleName
              .split(",")
              .map((item) =>
                h(
                  NTag,
                  { size: "small", type: "primary" },
                  { default: () => item }
                )
              ),
        }
      );
    },
  },
  {
    title: "邮箱",
    key: "email",
    render: (row) => {
      return row.email || "暂无";
    },
  },
  {
    title: "状态",
    key: "status",
    render(row) {
      return h(NSwitch, {
        value: row.status,
        uncheckedValue: 0,
        checkedValue: 1,
      });
    },
  },
  {
    title: "操作",
    key: "actions",
    fixed: "right",
    render(row) {
      return h(
        NSpace,
        { align: "center" },
        {
          default: () => [
            h(
              NButton,
              {
                strong: true,
                secondary: true,
                type: "error",
                size: "small",
                onClick() {
                  dialog.error({
                    title: "删除用户",
                    content: "你确定要删除用户吗？",
                    positiveText: "确认",
                    negativeText: "取消",
                    onPositiveClick(e) {
                      deleteUser({ ids: [row.id] })
                        .then((res) => {
                          message.success("删除成功");
                          loadData();
                        })
                        .catch((e) => {
                          message.error(`删除失败:${e}`);
                        });
                    },
                  });
                },
              },
              { default: () => "删除" }
            ),
            h(
              NButton,
              {
                strong: true,
                secondary: true,
                type: "success",
                size: "small",
                onClick() {
                  handleEditUser(row.id);
                },
              },
              { default: () => "编辑" }
            ),
          ],
        }
      );
    },
  },
];
const handleCreateUser = () => {
  console.log(userStore.userInfo.departmentId);
  Upsert.value.open({
    title: "创建用户",
    data: { departmentId: userStore.userInfo.departmentId },
  });
};
const handleEditUser = (id: number) => {
  getUserDetail({ id }).then((res) => {
    console.log(res);
    Upsert.value.open({ title: "修改用户", data: res["data"] });
  });
  // Upsert.value
};
const handleConfirm = ({ title, data }) => {
  console.log(title, data);
  if (title == "修改用户") {
    updateUser(data)
      .then((res) => {
        loadData();
        message.success("修改成功");
      })
      .catch((e) => {
        message.error("修改失败");
      });
  } else if (title == "创建用户") {
    addUser(data)
      .then((res) => {
        loadData();
        message.success("添加成功");
      })
      .catch((e) => {
        message.error("添加失败");
      });
  }
};
const loadData = () => {
  getFormUsers({
    departmentIds: [userStore.userInfo.departmentId],
    ...pagination.value,
  }).then((res: any) => {
    console.log(res);
    userList.value = res.data.list.filter(
      (item) => item.id != userStore.userInfo.id
    );
  });
};
onMounted(() => {
  loadData();
});
</script>

<style lang="scss" scoped>
.block-header {
  display: flex;
  align-items: center;
  .title {
    font-weight: bold;
    font-size: 24px;
  }
}
.row {
  display: flex;
  align-items: center;
  .row-label {
    font-weight: bold;
    margin-right: 12px;
  }
}
</style>
